<template>
  <ActionPanel>
    <el-form :model="data" label-width="auto">
      <el-form-item label="名称">
        <el-input v-model="name" @blur="validate"/>
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="data.label" />
      </el-form-item>
      <el-form-item  label="模式">
        <ElSelect v-model="data.mode">
          <ElOption label="弹窗显示" value="popup" />
          <ElOption label="内容区显示" value="content" />
        </ElSelect>
      </el-form-item>
      <el-form-item label="注释">
        <el-input type="textarea" v-model="data.comment" />
      </el-form-item>
      <el-form-item label="位置">
        <ElSelect v-model="data.position" multiple>
          <ElOption label="无" value="" />
          <ElOption label="导航栏" value="nav" />
          <ElOption label="个人中心" value="ucenter" />
          <ElOption label="菜单栏" value="menu" />
        </ElSelect>
      </el-form-item>
    </el-form>
    <template #footer>
      <ElButton type="primary" @click="doSave">保存</ElButton>
      <ElButton @click="close">关闭</ElButton>
    </template>
  </ActionPanel>
</template>
<script lang="ts" setup>
  import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus'
  import { currentApp, currentMicro } from '@/views/seed-dev'
  import { inject, ref } from 'vue';
  import { Home } from '@/views/types';
  import feedback from '@/utils/feedback';
  import { save } from '..';
  import { ActionPanel } from '@/components/ActionPanel';
  import { closePopupKey } from '@/components/Popup';

  const close = inject<() => void>(closePopupKey, void 0)
  function validate() {
    if (!name.value) {
      feedback.alertError('名称不能为空')
      return false
    }

    const microName = currentMicro.value
    const homes = microName ? currentApp.value.micros?.[microName]?.actions || {} : currentApp.value.homes || {}
    if(Object.keys(homes).includes(name.value)) {
      feedback.alertError(`【${name.value}】名称已存在`)
      return false
    }

    return true
  }

  const name = ref<string>()
  const data = ref<Home>({})

  function doSave() {
    validate() && save(name.value, data.value)
    close?.()
  }
</script>